package org.Lin.client;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class dbUtil {

    private static Connection conn;

    static {
        try {
            Properties props = new Properties();
            props.load(dbUtil.class.getClassLoader().getResourceAsStream("config.properties"));

            String url = props.getProperty("DB_URL");
            String user = props.getProperty("DB_USER");
            String password = props.getProperty("DB_PASSWORD");

            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addQuestion(String question, String userId) {
        String sql = "INSERT INTO questions (user, question) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, userId);
            pstmt.setString(2, question);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static List<questionModel> getAnsweredQuestions() {
        List<questionModel> list = new ArrayList<>();
        String sql = "SELECT * FROM questions WHERE status = 'answered' ORDER BY timestamp DESC LIMIT 20";
        try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                list.add(new questionModel(
                        rs.getInt("id"),
                        rs.getString("question"),
                        rs.getString("answer"),
                        rs.getString("model_used"),
                        rs.getObject("timestamp", LocalDateTime.class)
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

}